// @ts-nocheck
import React, { useState, useEffect, useRef } from 'react';
// 引入axios
import servers from '@/utlis/server';
// 引入antd-mobole
import { Swiper, Toast, Tabs, List, Button as Buadtdon } from 'antd-mobile';
import { RightOutlined } from '@ant-design/icons';
import { Button } from 'react-vant';
import { PlayOutline } from 'antd-mobile-icons';
// 引入jsonp
import jsonp from 'jsonp';

import { Select, Upload, DatePicker } from 'antd';
import { history } from 'umi';
// 引入头部区域
import Top from '@/component/Top';

import './index.less';
import '@/pages/golobo.less';
// 引入axios

// jsonp(`https://api.map.baidu.com/geocoding/v3/?address=${this.form.addres}&output=json&ak=7uIfaG0IpKfCuFNPGwX3KOXihxcgH3Mf&callback=showLocation`, null, async (err, state) => {
//   let { result: { location } } = state
//   console.log(location);
//   this.form.location = location
//   let { data } = await this.$axios.post('/shops/addstore', { form: this.form, user_id: this.userInfo._id })
//   if (data.code == 200) {
//       this.$message.success('添加店铺成功')
//       this.dialogFormVisible = false
//       this.form = {
//           name: '',
//           addres: "",
//           state: true
//       }
//       this.handleGetdata()
//   } else if (data.code == 204) {
//       this.$message.error(data.msg)

//   } else {
//       this.$message.error('添加店铺失败')
//   }
// })
export default function index() {
  // 定位容器div
  let Location = useRef();
  let [currentLocation, setCurrentLocation] = useState('');
  // 获取经度
  let [lat, setLat] = useState();
  // 获取维度
  let [lon, setLon] = useState();

  // 获取省份
  let [province, setProvince] = useState('');
  // 获取城市
  let [city, setCity] = useState('');
  // 获取行政区
  let [district, setDistrict] = useState('');
  // 获取街道
  let [street, setStreet] = useState('');
  // 获取街道号
  let [streetNumber, setStreetNumber] = useState('');
  // 显示今天日期
  let [taydate, settaydate] = useState(0);
  function showLocation() {
    let x = Location.current;
    //判断是否可以定位
    if (navigator.geolocation) {
      //getCurrentPosition()中需要传入一个回调函数
      navigator.geolocation.getCurrentPosition(location_1, showError);
    } else {
      x.innerHTML = '无法获取当前位置';
    }
  }
  function location_1(position) {
    const lon = position.coords.longitude;
    const lat = position.coords.latitude;
    setLon(lon);
    setLat(lat);

    // 显示获取到的用户定位中的纬度和经度
    // x.innerHTML = "纬度:" + position.coords.latitude + "经度:" + position.coords.longitude;
    // let lon = position.coords.longitude;
    var myGeo = new BMapGL.Geocoder();
    myGeo.getLocation(new BMapGL.Point(lon, lat), function (result) {
      if (result) {
        // console.log(result.addressComponents);
        // alert(JSON.stringify(result.addressComponents.province));
        setProvince((province = result.addressComponents.province));
        setCity((city = result.addressComponents.city));
        setDistrict((district = result.addressComponents.district));
        setStreet((street = result.addressComponents.street));
        setStreetNumber((streetNumber = result.addressComponents.streetNumber));
        // console.log(city);
        setCurrentLocation(
          (currentLocation = city + district + street + streetNumber),
        );
      }
    });
  }
  function showError(error) {
    //PERMISSION_DENIED 用户不允许地理定位
    //POSITON_UNAVAILABLE 无法获取当前位置
    let x = Location.current;
    //TIMEOUT 操作超时
    switch (error.code) {
      case error.PERMISSION_DENIED:
        x.innerHTML = '用户未开启地理定位';
        break;
      case error.POSITON_UNAVAILABLE:
        x.innerHTML = '无法获取当前位置';
        break;
      case error.TIMEOUT:
        x.innerHTML = '操作超时';
        break;
    }
  }

  useEffect(() => {
    showLocation();
    // ceshi();
    //  getTakeoutNav();
  }, []);
  // 添加测试数据
  let ceshi = async () => {
    let { data } = await servers.get('/ceshi');
    // console.log(data);
    setmovesdata(data.moves);
  };

  let [image, setimageUrl] = useState('');
  const [loading, setLoading] = useState(false);

  const uploadButton = (
    <div>
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  let [name, setname] = useState('');
  let [type, settype] = useState('');
  let [pin_numL, setpin_numL] = useState(0);
  let [self, setself] = useState('');
  let [move_id, setmove_id] = useState([]);
  let [movesdata, setmovesdata] = useState([]);
  const handleChange = (value: string[]) => {
    console.log(`selected ${value}`);
    setmove_id(value);
  };
  useEffect(() => {
    getSwiperdata();
    getpalydatas();
    gettuipaly();
  }, []);
  // 轮破图数据
  let [Swiperdata, setSwiperdata] = useState([]);
  // 热映数据
  let [repalydatas, setrepalydatas] = useState([]);
  // 即将上映
  let [awaitplays, setawaitplays] = useState([]);
  // 热门推荐
  let [tuipaly, settuipaly] = useState([]);
  // 获取轮破图
  let getSwiperdata = async () => {
    let { data } = await servers.get('/swiper');
    // console.log(data);
    setSwiperdata(data.data);
  };
  // 获取热映 待上映 推荐
  let getpalydatas = async () => {
    let { data } = await servers.get('/palydatas');
    console.log(data);
    setrepalydatas(data.replay);
    setawaitplays(data.awaitplays);
    settuipaly(data.tuipaly);
  };
  // 轮破图子元素
  const items = Swiperdata.map((img, index) => (
    <Swiper.Item key={index}>
      <div
        className="content"
        onClick={() => {
          Toast.show(`你点击了卡片 ${index + 1}`);
        }}
      >
        <img src={img} alt="" />
      </div>
    </Swiper.Item>
  ));
  // 底部推荐数据
  let [bottomtuidata, setbottomtuidata] = useState([]);
  // 热播数据
  let [bottomrebo, setbottomrebo] = useState([]);
  // 预告数据
  let [previewsdata, setpreviewsdata] = useState([]);
  // 获取底部推荐数据
  let gettuipaly = async () => {
    let { data } = await servers.get('/bottomtui');
    console.log(data.data);
    setbottomtuidata(data.data);
  };
  // 获取热播数据
  let getbottomrebo = async () => {
    let { data } = await servers.get('/bottomrebo');
    data = data.data.slice(0, 10);
    setbottomrebo(data);
  };
  // 获取预告数据
  let getpreviewsdata = async () => {
    let { data } = await servers.get('/getpreviews', {
      params: {
        pagenation: 'nopagenation',
      },
    });
    console.log(data);
    setpreviewsdata(data.data);
  };
  // 获取新片
  let [newplaysdata, setnewplaysdata] = useState([]);
  let getnewplays = async () => {
    let { data } = await servers.get('/getnewplays');
    setnewplaysdata(data.data);
  };
  const [hasMore, setHasMore] = useState(true);
  async function loadMore() {}
  // 底部默认激活
  let [activeKey, setactiveKey] = useState('tuijian');
  // TABSchange
  let TABSchange = async (key) => {
    console.log(key);
    if (key === 'tuijian') {
      gettuipaly();
    } else if (key === 'rebo') {
      getbottomrebo();
    } else if (key === 'yugao') {
      getpreviewsdata();
    } else {
      getnewplays();
    }
    setactiveKey(key);
  };
  // 设置热播榜排行样式
  let setstyle = (i) => {
    if (i == 0) {
      return {
        borderStyle: 'none',
        color: 'white',
        fontSize: '16px',
        backgroundColor: 'red',
      };
    } else if (i == 1) {
      return {
        color: '#fff',
        borderStyle: 'none',
        fontSize: '14px',
      };
    } else if (i == 2) {
      return {
        borderStyle: 'none',
        color: '#white',
        fontSize: '14px',
        backgroundColor: '#b058bd',
      };
    } else {
      return {};
    }
  };
  // 前去购票
  let gototicketing = (item) => {
    history.push({
      pathname: '/ticketing',
      state: { _id: item._id, item },
    });
  };
  // 前去电影详情
  let gotodetails = (item) => {
    console.log(item);
    if (item.paly_id) {
      console.log(111);
      history.push({
        pathname: '/details',
        state: {
          _id: item.paly_id._id,
        },
      });
    } else {
      history.push({
        pathname: '/details',
        state: {
          _id: item._id,
        },
      });
    }
  };
  return (
    <div className="home">
      <div
        className="hea"
        style={{ padding: '0.2rem 0', backgroundColor: '#fff' }}
      >
        <Top></Top>
      </div>
      <div className="swiper">
        {/* 轮播图 */}
        <Swiper autoplay loop>
          {items}
        </Swiper>
      </div>
      <div className="repaly">
        <p>
          热映影片 <RightOutlined />
        </p>
        <div className="repalydata">
          {repalydatas.map((item) => {
            return (
              <div className="box" key={item._id}>
                <img
                  src={item.paly_id.image}
                  onClick={() => {
                    gotodetails(item);
                  }}
                  alt=""
                />
                <h3>{item.paly_id.name}</h3>
                {/* <button className="palytype">{item.paly_id.type}</button> */}
                <button
                  block
                  shape="rounded"
                  className="goshop"
                  onClick={() => {
                    gototicketing(item);
                  }}
                >
                  购票
                </button>
              </div>
            );
          })}
        </div>
      </div>
      <div className="repaly">
        <p>
          即将上映 <RightOutlined />
        </p>
        <div className="repalydata">
          {awaitplays.map((item) => {
            return (
              <div className="box" key={item._id}>
                <img
                  src={item.paly_id.image}
                  alt=""
                  onClick={() => {
                    gotodetails(item);
                  }}
                />
                <h3>{item.paly_id.name}</h3>
                {/* <button className="palytype">{item.paly_id.type}</button> */}
                <button
                  block
                  shape="rounded"
                  className="goshop"
                  onClick={() => {
                    gototicketing(item);
                  }}
                >
                  购票
                </button>
              </div>
            );
          })}
        </div>
      </div>
      <div className="repaly">
        <p>
          热门推荐 <RightOutlined />
        </p>
        <div className="repalydata">
          {tuipaly.map((item) => {
            return (
              <div className="box" key={item._id}>
                <img
                  src={item.paly_id.image}
                  alt=""
                  onClick={() => {
                    gotodetails(item);
                  }}
                />
                <h3>{item.paly_id.name}</h3>
                {/* <button className="palytype">{item.paly_id.type}</button> */}
                <button
                  block
                  shape="rounded"
                  className="goshop"
                  onClick={() => {
                    gototicketing(item);
                  }}
                >
                  购票
                </button>
              </div>
            );
          })}
        </div>
      </div>
      <div className="plpaly">
        <Tabs activeKey={activeKey} onChange={TABSchange}>
          <Tabs.Tab title="推荐" key="tuijian" destroyOnClose={true}>
            {bottomtuidata.map((item) => {
              return (
                <div key={item._id} className="bottomtui_box">
                  <p className="bottomtui_title"> {item.title}</p>
                  <div className="bottomtui_img">
                    {item.imgs.map((img, i) => {
                      return (
                        <img
                          src={img}
                          key={i}
                          style={{
                            width:
                              item.imgs.length == 3 ? 'calc(100% / 3)' : '100%',
                          }}
                          alt=""
                        />
                      );
                    })}
                  </div>
                  <div className="bottomtui_bottom">
                    <span>{item.critics_id.length}条评论</span>
                  </div>
                </div>
              );
            })}
          </Tabs.Tab>
          <Tabs.Tab title="热播榜" key="rebo" destroyOnClose={true}>
            <ul className="rebo_ul">
              {bottomrebo.map((item, i) => {
                return (
                  <li key={item._id}>
                    <img
                      src={item.paly_id.image}
                      alt={item.paly_id.name}
                      onClick={() => {
                        gotodetails(item);
                      }}
                    />
                    <div>
                      <span className="itemname"> {item.paly_id.name}</span>
                      <p className="itemself">{item.paly_id.self}</p>
                    </div>
                    <span className="nosort" style={setstyle(i)}>
                      NO.{i + 1}
                    </span>
                  </li>
                );
              })}
            </ul>
          </Tabs.Tab>
          <Tabs.Tab title="预告片" key="yugao" destroyOnClose={true}>
            <List>
              {previewsdata.map((item) => {
                return (
                  <List.Item key={item._id}>
                    <div className="plre_box">
                      <img src={item.paly_id.image} alt="" />
                      <span
                        className="playicon_box"
                        onClick={() => {
                          console.log(item);
                        }}
                      >
                        <PlayOutline
                          onClick={() => {
                            // console.log(item);
                            history.push({
                              pathname: '/yugao',
                              state: { _id: item.paly_id._id },
                            });
                          }}
                        />
                      </span>
                      <div>
                        <h5>{item.paly_id.name}</h5>
                        <p>{item.paly_id.self}</p>
                      </div>
                    </div>
                  </List.Item>
                );
              })}
            </List>
          </Tabs.Tab>
          <Tabs.Tab title="新片上映" key="xin" destroyOnClose={true}>
            {/* <div className='newplays'>
              {newplaysdata.}
            </div> */}
            <List>
              {newplaysdata.map((item) => {
                return (
                  <List.Item key={item._id}>
                    <div className="newplays">
                      <img
                        src={item.image}
                        alt=""
                        onClick={() => {
                          gotodetails(item);
                        }}
                      />
                      <div>
                        <h5>
                          {item.name}
                          <Buadtdon
                            size="mini"
                            shape="rounded"
                            color="danger"
                            onClick={() => {
                              gototicketing(item);
                            }}
                          >
                            购票
                          </Buadtdon>
                        </h5>
                        <p>{item.self}</p>
                      </div>
                    </div>
                  </List.Item>
                );
              })}
            </List>
          </Tabs.Tab>
        </Tabs>
      </div>
      {/* <div>
        <p>
          电影名称{' '}
          <input
            type="text"
            onChange={(e) => {
              setname(e.target.value);
            }}
          />
        </p>
        <p>
          图片{' '}
          <Upload
            name="avatar"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            action="http://localhost:3000/img"
            onSuccess={(value) => {
              // console.log(value);
              setimageUrl('http://localhost:3000/' + value.imgurl);
            }}
          >
            {image ? (
              <img src={image} alt="avatar" style={{ width: '100%' }} />
            ) : (
              uploadButton
            )}
          </Upload>
        </p>
        <p>
          电影类型{' '}
          <input
            type="text"
            onChange={(e) => {
              // console.log(e.target.value);
              settype(e.target.value);
            }}
          />
        </p>
        <p>
          评分{' '}
          <input
            type="number"
            name=""
            id=""
            onChange={(e) => {
              setpin_numL(e.target.value);
            }}
          />
        </p>
        <p>
          简介{' '}
          <input
            type="text"
            name=""
            id=""
            onChange={(e) => {
              setself(e.target.value);
            }}
          />
        </p>
        <p>
          放映影院{' '}
          <Select
            mode="multiple"
            allowClear
            style={{ width: '100%' }}
            placeholder="Please select"
            defaultValue={[]}
            onChange={handleChange}
            options={movesdata.map((item) => {
              return {
                label: item.name,
                value: item._id,
              };
            })}
          />
        </p>
        <button
          onClick={async () => {
            let form = {
              name,
              image,
              type,
              pin_numL,
              self,
              move_id,
            };
            let { data } = await servers.post('/addplay', form);
            // console.log(data);
          }}
        >
          添加
        </button>
      </div> */}
    </div>
  );
}
